<template>
  <el-dialog :title="'设备授权'" v-model="visible"
             :close-on-click-modal="false" draggable>
    <el-row style="height: 50px">
      <el-form>
        <el-form-item>
          <el-select v-model="thisPageState.authorizeCategory" @change="authorizeCategorySelectChange"  placeholder="请选择授权类型">
            <el-option :key="index" :label="item.name" :value="item.id" v-for="(item, index) in thisPageState.authorizeCategoryList"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-row>
    <el-table :data="thisPageState.tableDataList" v-loading="thisPageState.loading" border
              :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
              @selection-change="selectionChangHandle"
              @sort-change="sortChangeHandle">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column type="index" label="#" width="40" />
      <el-table-column prop="categoryName" label="分类名称"  show-overflow-tooltip/>
      <el-table-column prop="categoryCode" label="分类编码"  show-overflow-tooltip/>
      <el-table-column prop="categoryDesc" label="分类描述"  show-overflow-tooltip/>
      <el-table-column prop="createBy" label="创建者"  show-overflow-tooltip/>
      <el-table-column prop="createTime" label="创建时间"  show-overflow-tooltip/>
      <el-table-column prop="updateTime" label="更新时间"  show-overflow-tooltip/>
    </el-table>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading || (multiple)" >
            {{ thisPageState.authorizeCategory===thisPageState.authorizeCategoryList[1].id ? '解除授权' : '授权'  }}
          </el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="devAuthorize">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/ai/aiModel'
import { rule } from '/@/utils/validate';
import {BasicTableProps, useTable} from "/@/hooks/table";
import {fetchListByNotInIds,fetchListByInIds} from "/@/api/iot/iotDeviceCategory";
import {fetchList as fetchAiModelDevCategoryList,addObjBatch as addAiModelDevCategoryBatch,
  delObjsByDevCategoryIdsAndModelId as delAiModelCategoryByDevCategoryIdsAndModelId} from "/@/api/ai/aiModelDevCategory";

const emit = defineEmits(['refresh']);

// 定义变量内容
const visible = ref(false)
const loading=ref(false)
// 定义字典




// 打开弹窗
const openAuthorizeDialog = (id: string) => {
  visible.value = true
  //默认显示的授权设备
  thisPageState.authorizeCategory=thisPageState.authorizeCategoryList[0].id
  // 获取aiModel信息
  if (id) {
    thisPageState.modelId=id;//更新页面的modelId
    getDevCategoryByModel(id)
  }
  // 重置表单数据
  nextTick(() => {

  });


};

// 提交
const onSubmit = async () => {


  try {
    loading.value = true;
    if(selectObjs.value.length>0){
      if(thisPageState.authorizeCategory===thisPageState.authorizeCategoryList[1].id){
      //  解除授权
        const res =await delAiModelCategoryByDevCategoryIdsAndModelId(selectObjs.value,thisPageState.modelId)
        if(res.data){
          useMessage().success('结仇设备授权成功');
        }
      }else{
        //授权
        //需要更新的数据列表,
        const updateList=[]
        selectObjs.value.map(itemId=>{
          updateList.push({
            modelId:thisPageState.modelId,
            devCategoryId:itemId
          })
        })
        const res =await addAiModelDevCategoryBatch(updateList)
        if(res.data){
          useMessage().success('授权设备成功');
        }
      }

    }
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

/**
 * 获取当前模型还没有授权的设备--------------------------------------
 */

// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)


/**
 * 原始获取表数据的 钩子函数 此处不用
 */
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: null,
})
//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)


/**
 * 页面数据状态
 */
const thisPageState=reactive({
  tableDataList:[],
  loading:false,
  modelId:null,
  authorizeCategoryList:[
    {
      id:"0",
      name:"授权",
    },
    {
      id:"1",
      name:"解除授权"
    }
  ],
  authorizeCategory:"0",
})


/**
 * 获取数据
 * isAuthorized 表示是否获取已经授权的数据
 */
async function getDevCategoryByModel(aiModelId){
  thisPageState.loading=true
  const res=await fetchAiModelDevCategoryList({modelId:aiModelId})
  const bindedList=res.data
  let bindedDevCategoryIdList=[]
  if(bindedList.length>0){
    bindedDevCategoryIdList=bindedList.map(item=>item.devCategoryId)
  }
  let isAuthorized=false;
  if(thisPageState.authorizeCategory===thisPageState.authorizeCategoryList[1].id){
  //  如果是解除授权就获取已经授权的设备
    isAuthorized=true
  }
  const res2=isAuthorized ? await fetchListByInIds(bindedDevCategoryIdList) : await fetchListByNotInIds(bindedDevCategoryIdList)
  thisPageState.tableDataList=res2.data
  thisPageState.loading=false
}


/**
 * 表格多选事件
 */
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};


/**
 * 授权类别改变 是授权还是解除授权
 */
async function authorizeCategorySelectChange(){
  //刷新数据
  getDevCategoryByModel(thisPageState.modelId)
}


// 暴露变量
defineExpose({
  openAuthorizeDialog
});
</script>